package cn.com.b2office.struts2.servlet;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import cn.com.b2office.domain.ExData;
import cn.com.b2office.exchange.ExInstruction;
import cn.com.b2office.service.ExService;

public class DataExchangeServlet extends HttpServlet {

	private static final long serialVersionUID = -822510258028332152L;

	private ExService exService = null;

	public void init() throws ServletException {
		WebApplicationContext ctx = WebApplicationContextUtils
				.getRequiredWebApplicationContext(this.getServletContext());
		exService = (ExService) ctx.getBean("exService");
	}

	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			ObjectInputStream in = new ObjectInputStream(request
					.getInputStream());
			Object data = in.readObject();
			in.close();

			Object echo = null;
			if (data instanceof ExData) {
				echo = exService.process((ExData) data);
			} else if (data instanceof ExInstruction) {
				echo = exService.findExData(100);
			}

			response.setContentType("application/octet-stream");
			ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
			ObjectOutputStream out = new ObjectOutputStream(byteOut);
			out.writeObject(echo);
			out.flush();
			out.close();
			byte[] buf = byteOut.toByteArray();
			response.setContentLength(buf.length);
			ServletOutputStream servletOut = response.getOutputStream();
			servletOut.write(buf);
			servletOut.flush();
			servletOut.close();

		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			// temporarily do nothing ...
		}

	}

}
